<?php

// this script can take several minutes to execute
set_time_limit(600);
error_reporting(E_ALL);

if(!class_exists('Antz')) die('Antz tookit is required: http://dev.cmsmadesimple.org/projects/antz/');
$DB = Antz::registry('db');
$USER = Antz::registry('user');

// first, we uninstall previous version to start with a clean slate
$this->Uninstall();

//$DB->debug(true);
//$DB->showErrors(true);
//$haltInstall = true;

global $gCms;


$dirname = dirname(__FILE__);
$dirname = str_replace(DIRECTORY_SEPARATOR, '/', $dirname);

$error = false;


$this->removeHooksFromCore();
$this->addHooksToCore();


echo __FILE__.__LINE__;








if($gCms->config['dbms']=='postgres7'){
    // postgresql setup

    $tablesFile = 'tables.pgsql.sql';
    ob_start();
    include($tablesFile);
    $tableDefinition = ob_get_contents();
    ob_end_clean();


    // add the system prefix to the tables
    $tableDefinition = str_replace('prefix_', cms_db_prefix(), $tableDefinition);
    /*
    $sr = Antz::newObject('Antz_Db_SqlReader');
    $sr->setQuery($tableDefinition);
    // create our tables
    while($q = $sr->nextQuery()){
        $DB->query($q);
    };*/
    $tableDefinition = explode(';', $tableDefinition);
    foreach($tableDefinition as $k=>$v){
        $DB->query($v);
    };

    // add the config settings
    if(file_exists('bup_config.txt')){
        $DB->query("COPY TABLE {$this->config['db_prefix']}iusers_config FROM '{$dirname}/bup_config.txt'");
    }else{
        ob_start();
        include($dirname.'/config.sql');
        $config = ob_get_contents();
        ob_end_clean();
        $config = str_replace('prefix_', cms_db_prefix(), $config);
        $config = explode(';', $config);
        foreach($config as $k=>$v){
            $DB->query($v);
        };
    };

    if(file_exists($dirname.'/bup_users.txt')){
        $DB->query("COPY {$this->config['db_prefix']}iusers FROM '{$dirname}/bup_users.txt'");
    };
    if(file_exists($dirname.'/bup_user_groups.txt')){
        $DB->query("COPY {$this->config['db_prefix']}iusers_groups FROM '{$dirname}/bup_groups.txt'");
    };
    if(file_exists($dirname.'/bup_users_to_groups.txt')){
        $DB->query("COPY {$this->config['db_prefix']}iusers_to_groups FROM '{$dirname}/bup_users_to_groups.txt'");
    };
    if(file_exists($dirname.'/bup_fe_history.txt')){
        $DB->query("COPY {$this->config['db_prefix']}iusers_history FROM '{$dirname}/bup_history.txt'");
    };
    if(file_exists($dirname.'/bup_countries.txt')){
        $DB->query("COPY {$this->config['db_prefix']}iusers_countries FROM '{$dirname}/bup_countries.txt'");
    }elseif(file_exists($dirname.'/countries.txt')){
        $DB->query("COPY {$this->config['db_prefix']}iusers_countries FROM '{$dirname}/countries.txt'");
    };
    if(file_exists($dirname.'/bup_cities.txt')){
        $DB->query("COPY {$this->config['db_prefix']}iusers_cities FROM '{$dirname}/bup_cities.txt'");
    }else{
        $DB->query("COPY {$this->config['db_prefix']}iusers_cities FROM '{$dirname}/cities.txt'");
    };
    if(file_exists($dirname.'/bup_pages_to_groups.txt')){
        // load page permission settings from the last installation
        $DB->query("COPY {$this->config['db_prefix']}iusers_pages_to_groups FROM '{$dirname}/bup_pages_to_groups.txt'");
    }else{
        // we have to make sure all pages get a permission setting, preventing the pages from being inaccessible
        $pages = $DB->fetchAll("SELECT content_id FROM {$this->config['db_prefix']}content");

        foreach($pages as $k=>$v){
            if($DB->countRows(cms_db_prefix().'iusers_pages_to_groups', "page_id = '{$v['content_id']}'") == 0)
                $DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$v['content_id'], 'group_key'=>'public'));
        };
    };


    // ending postgresql setup

}else if($gCms->config['dbms']=='mysql'){
    // mysql setup

    $tablesFile = 'tables.mysql.sql';
    ob_start();
    include($tablesFile);
    $tableDefinition = ob_get_contents();
    ob_end_clean();


    // add the system prefix to the tables
    $tableDefinition = str_replace('prefix_', cms_db_prefix(), $tableDefinition);
    /*
    $sr = Antz::newObject('Antz_Db_SqlReader');
    $sr->setQuery($tableDefinition);
    // create our tables
    while($q = $sr->nextQuery()){
        $DB->query($q);
    };*/
    $tableDefinition = explode(';', $tableDefinition);
    foreach($tableDefinition as $k=>$v){
        $DB->query($v);
    };

    // add the config settings
    if(file_exists('bup_config.txt')){
        $DB->query("LOAD DATA INFILE '{$dirname}/bup_config.txt' INTO TABLE {$this->config['db_prefix']}iusers_config");
    }else{
        ob_start();
        include($dirname.'/config.sql');
        $config = ob_get_contents();
        ob_end_clean();
        $config = str_replace('prefix_', cms_db_prefix(), $config);
        $config = explode(';', $config);
        foreach($config as $k=>$v){
            $DB->query($v);
        };
    };

    if(file_exists($dirname.'/bup_users.txt')){
        $DB->query("LOAD DATA INFILE '{$dirname}/bup_users.txt' INTO TABLE {$this->config['db_prefix']}iusers");
    };
    if(file_exists($dirname.'/bup_user_groups.txt')){
        $DB->query("LOAD DATA INFILE '{$dirname}/bup_groups.txt' INTO TABLE {$this->config['db_prefix']}iusers_groups");
    };
    if(file_exists($dirname.'/bup_users_to_groups.txt')){
        $DB->query("LOAD DATA INFILE '{$dirname}/bup_users_to_groups.txt' INTO TABLE {$this->config['db_prefix']}iusers_to_groups");
    };
    if(file_exists($dirname.'/bup_fe_history.txt')){
        $DB->query("LOAD DATA INFILE '{$dirname}/bup_history.txt' INTO TABLE {$this->config['db_prefix']}iusers_history");
    };
    if(file_exists($dirname.'/bup_countries.txt')){
        $DB->query("LOAD DATA INFILE '{$dirname}/bup_countries.txt' INTO TABLE {$this->config['db_prefix']}iusers_countries");
    }elseif(file_exists($dirname.'/countries.txt')){
        $DB->query("LOAD DATA INFILE '{$dirname}/countries.txt' INTO TABLE {$this->config['db_prefix']}iusers_countries");
    };
    if(file_exists($dirname.'/bup_cities.txt')){
        $DB->query("LOAD DATA INFILE '{$dirname}/bup_cities.txt' INTO TABLE {$this->config['db_prefix']}iusers_cities");
    }else{
        $DB->query("LOAD DATA INFILE '{$dirname}/cities.txt' INTO TABLE {$this->config['db_prefix']}iusers_cities");
    };
    if(file_exists($dirname.'/bup_pages_to_groups.txt')){
        // load page permission settings from the last installation
        $DB->query("LOAD DATA INFILE '{$dirname}/bup_pages_to_groups.txt' INTO TABLE {$this->config['db_prefix']}iusers_pages_to_groups");
    }else{
        // we have to make sure all pages get a permission setting, preventing the pages from being inaccessible
        $pages = $DB->fetchAll("SELECT content_id FROM {$this->config['db_prefix']}content");

        foreach($pages as $k=>$v){
            if($DB->countRows(cms_db_prefix().'iusers_pages_to_groups', "page_id = '{$v['content_id']}'") == 0)
                $DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$v['content_id'], 'group_key'=>'public'));
        };
    };


    // ending mysql setup

};



// create our default user groups
$DB->insert(cms_db_prefix().'iusers_groups', array('keyname'=>'public', 'title'=>'Public'));
$DB->insert(cms_db_prefix().'iusers_groups', array('keyname'=>'private', 'title'=>'Private'));
$DB->insert(cms_db_prefix().'iusers_to_groups', array('group_key'=>'public', 'user_id'=>0));






$sitename = $DB->oneValue(cms_db_prefix().'siteprefs', 'sitepref_value', "sitepref_name = 'sitename'");
$templateId = $DB->oneValue(cms_db_prefix().'templates', 'template_id', "template_id > 0 AND default_template = 1");

// create the register page
$alias = 'register';
while($DB->countRows(cms_db_prefix().'content', "content_alias = '{$alias}'")>0) $alias .= '1';
$pageParams = array(
    'content_type' => 'content',
    'title' => 'Register with '.$sitename,
    'menutext' => 'Register',
    'access_groups' => 'public,private',
    'template_id' => $templateId,
    'content_en' => '{cms_module module="'.$this->GetName().'" action="register"}',
    'firsttime' => 0,
    'orig_content_type' => 'content',
    'active' => 'on',
    'showinmenu' => 'on',
    'cachable' => 'on',
    'alias' => $alias
);
$pageid = $this->AddPage($pageParams, 'Register with '.$sitename, 'register');
$DB->update(cms_db_prefix().'iusers_config', array('v'=>$pageid), "k = 'register_id'");
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'public'));
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'private'));

// create the login page
$alias = 'login';
while($DB->countRows(cms_db_prefix().'content', "content_alias = '{$alias}'")>0) $alias .= '1';
$pageParams = array(
    'content_type' => 'content',
    'title' => 'Login to '.$sitename,
    'menutext' => 'Login',
    'access_groups' => 'public,private',
    'template_id' => $templateId,
    'content_en' => '{cms_module module="'.$this->GetName().'" action="login"}',
    'firsttime' => 0,
    'orig_content_type' => 'content',
    'active' => 'on',
    'showinmenu' => 'on',
    'cachable' => 'on',
    'alias' => $alias
);
$pageid = $this->AddPage($pageParams, 'Login to '.$sitename, 'login');
$DB->update(cms_db_prefix().'iusers_config', array('v'=>$pageid), "k = 'login_id'");
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'public'));
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'private'));

// create the logout page
$alias = 'logout';
while($DB->countRows(cms_db_prefix().'content', "content_alias = '{$alias}'")>0) $alias .= '1';
$pageParams = array(
    'content_type' => 'content',
    'title' => 'Logout of '.$sitename,
    'menutext' => 'Logout',
    'access_groups' => 'public,private',
    'template_id' => $templateId,
    'content_en' => '{cms_module module="'.$this->GetName().'" action="logout"}',
    'firsttime' => 0,
    'orig_content_type' => 'content',
    'active' => 'on',
    'showinmenu' => 'on',
    'cachable' => 'on',
    'alias' => $alias
);
$pageid = $this->AddPage($pageParams, 'Logout of '.$sitename, 'logout');
$DB->update(cms_db_prefix().'iusers_config', array('v'=>$pageid), "k = 'logout_id'");
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'public'));
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'private'));

// create the verify_email page
$alias = 'verify';
while($DB->countRows(cms_db_prefix().'content', "content_alias = '{$alias}'")>0) $alias .= '1';
$pageParams = array(
    'content_type' => 'content',
    'title' => 'Verify email',
    'menutext' => 'Verify email',
    'access_groups' => 'public,private',
    'template_id' => $templateId,
    'content_en' => '{cms_module module="'.$this->GetName().'" action="verify_email"}',
    'firsttime' => 0,
    'orig_content_type' => 'content',
    'active' => 'on',
    'showinmenu' => '0',
    'cachable' => 'on',
    'alias' => $alias
);
$pageid = $this->AddPage($pageParams, 'Verify email', 'verify_email');
$DB->update(cms_db_prefix().'iusers_config', array('v'=>$pageid), "k = 'email_verification_id'");
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'public'));
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'private'));
$DB->update(cms_db_prefix().'content', array('show_in_menu'=>0), "content_id = '{$pageid}'");

// create the profile page
$alias = 'profile';
while($DB->countRows(cms_db_prefix().'content', "content_alias = '{$alias}'")>0) $alias .= '1';
$pageParams = array(
    'content_type' => 'content',
    'title' => 'Update profile',
    'menutext' => 'Update profile',
    'access_groups' => 'private',
    'template_id' => $templateId,
    'content_en' => '{cms_module module="'.$this->GetName().'" action="profile"}',
    'firsttime' => 0,
    'orig_content_type' => 'content',
    'active' => 'on',
    'showinmenu' => 'on',
    'cachable' => 'on',
    'alias' => $alias
);
$pageid = $this->AddPage($pageParams, 'Update profile '.$sitename, 'profile');
$DB->update(cms_db_prefix().'iusers_config', array('v'=>$pageid), "k = 'profile_id'");
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'private'));

// create the terms and conditions page
$alias = 'tnc';
while($DB->countRows(cms_db_prefix().'content', "content_alias = '{$alias}'")>0) $alias .= '1';
$pageParams = array(
    'content_type' => 'content',
    'title' => 'Terms and conditions',
    'menutext' => 'Terms and conditions',
    'access_groups' => 'public,private',
    'template_id' => $templateId,
    'content_en' => '{cms_module module="'.$this->GetName().'" action="tnc"}',
    'firsttime' => 0,
    'orig_content_type' => 'content',
    'active' => 'on',
    'showinmenu' => 'on',
    'cachable' => 'on',
    'alias' => $alias
);
$pageid = $this->AddPage($pageParams, 'Terms and conditions', 'tnc');
$DB->update(cms_db_prefix().'iusers_config', array('v'=>$pageid), "k = 'tnc_id'");
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'private'));
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'public'));


// create the password retrieval page
$alias = 'lost-password';
while($DB->countRows(cms_db_prefix().'content', "content_alias = '{$alias}'")>0) $alias .= '1';
$pageParams = array(
    'content_type' => 'content',
    'title' => 'Lost password',
    'menutext' => 'Lost password',
    'access_groups' => 'public,private',
    'template_id' => $templateId,
    'content_en' => '{cms_module module="'.$this->GetName().'" action="lost_password"}',
    'firsttime' => 0,
    'orig_content_type' => 'content',
    'active' => 'on',
    'showinmenu' => 'on',
    'cachable' => 'on',
    'alias' => $alias
);
$pageid = $this->AddPage($pageParams, 'Lost password', 'lost-password');
$DB->update(cms_db_prefix().'iusers_config', array('v'=>$pageid), "k = 'lost_password_id'");
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'private'));
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'public'));

/* reserved until language versions become available
$alias = 'change-country';
while($DB->countRows(cms_db_prefix().'content', "content_alias = '{$alias}'")>0) $alias .= '1';
$pageParams = array(
    'content_type' => 'content',
    'title' => 'Change your country',
    'menutext' => 'IUsers change country',
    'access_groups' => implode(',', $accessGroups),
    'template_id' => $templateId,
    'content_en' => '{cms_module module="'.$this->GetName().'" action="change_country"}',
    'firsttime' => 0,
    'orig_content_type' => 'content',
    'active' => 'on',
    'showinmenu' => '0',
    'cachable' => 'on',
    'alias' => $alias
);
$pageid = $this->AddPage($pageParams, $this->GetName().' change country', 'change_country');
$DB->update(cms_db_prefix().'iusers_config', array('v'=>$alias), "k = 'change_country_url'");
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'private'));
$DB->insert(cms_db_prefix().'iusers_pages_to_groups', array('page_id'=>$pageid, 'group_key'=>'public'));
*/


// create our permissions in the system that will enable us to restrict access to the module
$this->CreatePermission($this->GetName().' Config', 'Configuration settings for '.$this->GetName());
$this->CreatePermission($this->GetName().' Users', 'View and manage users in '.$this->GetName());
$this->CreatePermission($this->GetName().' Groups', 'View and manage groups in '.$this->GetName());
$this->CreatePermission($this->GetName().' Places', 'View and manage countries and cities in '.$this->GetName());















if($haltInstall) exit;

